import { readFileSync, existsSync, statSync } from "fs";
import { defineEventHandler, setHeader } from "h3";
import { join, extname } from "path";

export default defineEventHandler(async (event) => {
  const filename = getRouterParam(event, 'filename');
  
  if (!filename) {
    throw createError({
      statusCode: 400,
      statusMessage: "Filename is required",
    });
  }

  // Decode URL-encoded filename
  const decodedFilename = decodeURIComponent(filename);
  
  const shareDir = "share-lan";
  const filePath = join(shareDir, decodedFilename);

  if (!existsSync(filePath)) {
    throw createError({
      statusCode: 404,
      statusMessage: "File not found",
    });
  }

  // Get file stats
  const stats = statSync(filePath);
  
  // Set appropriate headers for preview (not download)
  const ext = extname(decodedFilename).toLowerCase();
  const mimeTypes: Record<string, string> = {
    '.pdf': 'application/pdf',
    '.txt': 'text/plain; charset=utf-8',
    '.json': 'application/json; charset=utf-8',
    '.js': 'text/javascript; charset=utf-8',
    '.ts': 'text/typescript; charset=utf-8',
    '.vue': 'text/plain; charset=utf-8',
    '.html': 'text/html; charset=utf-8',
    '.css': 'text/css; charset=utf-8',
    '.md': 'text/markdown; charset=utf-8',
    '.xml': 'text/xml; charset=utf-8',
    '.csv': 'text/csv; charset=utf-8',
    '.log': 'text/plain; charset=utf-8',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.png': 'image/png',
    '.gif': 'image/gif',
    '.webp': 'image/webp',
    '.svg': 'image/svg+xml',
    '.bmp': 'image/bmp',
    '.mp4': 'video/mp4',
    '.webm': 'video/webm',
    '.ogg': 'video/ogg',
    '.avi': 'video/x-msvideo',
    '.mov': 'video/quicktime',
    '.mp3': 'audio/mpeg',
    '.wav': 'audio/wav',
    '.m4a': 'audio/mp4',
    '.aac': 'audio/aac',
    '.zip': 'application/zip',
    '.doc': 'application/msword',
    '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  };

  const mimeType = mimeTypes[ext] || 'application/octet-stream';

  console.log(`Preview request for: ${decodedFilename}`);
  
  setHeader(event, 'Content-Type', mimeType);
  setHeader(event, 'Content-Length', stats.size);
  
  // 设置为内联显示而不是下载
  setHeader(event, 'Content-Disposition', `inline; filename="${filename}"`);
  
  // 添加跨域头以支持预览
  setHeader(event, 'Access-Control-Allow-Origin', '*');
  setHeader(event, 'Access-Control-Allow-Methods', 'GET');
  
  // 对于文本文件，确保返回UTF-8编码
  const textExtensions = ['.txt', '.json', '.js', '.ts', '.vue', '.html', '.css', '.md', '.xml', '.csv', '.log'];
  
  if (textExtensions.includes(ext)) {
    try {
      // 尝试以UTF-8读取文本文件
      const content = readFileSync(filePath, 'utf-8');
      return content;
    } catch {
      // 如果UTF-8读取失败，回退到二进制读取
      console.warn(`Failed to read ${decodedFilename} as UTF-8, falling back to binary`);
      return readFileSync(filePath);
    }
  } else {
    // 对于非文本文件，直接返回二进制内容
    return readFileSync(filePath);
  }
}); 